﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Data;
using System.Windows.Media.Imaging;
using Windows8Accelerator.Core.Xaml.Caching;
using Windows8Accelerator.Core.Xaml.Storage;

namespace Windows8Accelerator.Core.Xaml.Converters
{
    public class StringToImageConverter : IValueConverter
    {
        private static Uri _baseUri = new Uri("ms-appx:///");

        public bool UseCache { get; set; }

        public string LocalPrefix { get; set; }

        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            try
            {
                if (value == null)
                    return null;
                var url = (string)value;

                Uri uri;
                if (url.ToUpper().Contains("HTTP://") || url.ToUpper().Contains("HTTPS://"))
                {
                    uri = new Uri(url);
                    if (UseCache || (parameter is string && ((string)parameter).ToUpper().Equals("CACHE")))
                    {
                        uri = CacheManager.GetOrRetrieveUri(uri);
                    }
                }
                else if (!string.IsNullOrEmpty(LocalPrefix))
                {
                    uri = new Uri(LocalPrefix + url, UriKind.Relative);
                }
                else
                {
                    uri = new Uri(_baseUri, url);
                }

                if (uri.IsAbsoluteUri && uri.Scheme.Equals("ms-appdata"))
                {
                    if (uri.Segments.Length == 4)
                    {
                        if (uri.Segments[2].Equals("__uricache__/"))
                        {
                            var sourceFile = StorageHelper.OpenLocalFile(Path.Combine("__uricache__", WebUtility.UrlDecode(uri.Segments[3])));
                            if (sourceFile == null)
                                return null;
                            using (sourceFile)
                            {
                                BitmapImage bm = new BitmapImage();
                                bm.SetSource(sourceFile);
                                return bm;
                            }
                        }
                    }
                }

                return new BitmapImage(uri);
            }
            catch (Exception e)
            {
                e.ToString();
            }
            return null;
        }


        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
}
